package qianting.news.service.logger.service.impl;

import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import qianting.news.apis.models.logger.dtos.LoggerSearchDto;
import qianting.news.common.entity.State;
import qianting.news.service.logger.service.LoggerService;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class LoggerServiceImpl implements LoggerService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;


    @Override
    public State search(LoggerSearchDto dto) throws IOException {

        SearchRequest searchRequest = new SearchRequest("qianting-news-logs");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //布尔查询
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

        //时间范围
        boolQueryBuilder.must(QueryBuilders.rangeQuery("@timestamp")
                .gte(dto.getBeginTime())
                .lte(dto.getEndTime())
                .format("strict_date_optional_time"));

        //字段查询
        if (dto.getServer() != null && !dto.getServer().isEmpty()) {
            boolQueryBuilder.must(QueryBuilders.matchQuery("service.keyword", dto.getServer()));
        }

        if (dto.getLevel() != null && !dto.getLevel().isEmpty()) {
            boolQueryBuilder.must(QueryBuilders.matchQuery("logLevel.keyword", dto.getLevel()));
        }

        if (dto.getMessage() != null && !dto.getMessage().isEmpty()) {
            boolQueryBuilder.must(QueryBuilders.matchQuery("message", dto.getMessage()));
        }
        //分页查询
        searchSourceBuilder.from(dto.getPage());
        searchSourceBuilder.size(dto.getSize());

        //设置排序方式
        searchSourceBuilder.sort("@timestamp", dto.getOrder()==0 ? SortOrder.DESC : SortOrder.ASC);

        //设置高亮  title
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("message");
        highlightBuilder.preTags("<font style='color: green; font-size: inherit;'>");
        highlightBuilder.postTags("</font>");
        searchSourceBuilder.highlighter(highlightBuilder);

        //开始查询
        searchSourceBuilder.query(boolQueryBuilder);
        searchRequest.source(searchSourceBuilder);
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

        //3.结果封装返回

        List<Map> list = new ArrayList<>();

        SearchHit[] hits = searchResponse.getHits().getHits();
        for (SearchHit hit : hits) {
            String json = hit.getSourceAsString();
            Map map = JSON.parseObject(json, Map.class);
            //处理高亮
            if(hit.getHighlightFields() != null && hit.getHighlightFields().size() > 0){
                Text[] titles = hit.getHighlightFields().get("message").getFragments();
                String title = StringUtils.join(titles);
                //高亮标题
                map.put("h_message",title);
            }else {
                //原始标题
                map.put("h_message",map.get("message"));
            }
            list.add(map);
        }

        return State.succ(list);
    }

}
